import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@WebServlet("/cookie")
public class CookieServlet extends HttpServlet {
    /**
     * 写cookie
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie=new Cookie("myCookie","Hello:"+ LocalDateTime.now());
        resp.addCookie(cookie);
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().println("Cookie 添加成功");
    }

    /**
     * cookie读取
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies=req.getCookies();
        StringBuilder builder=new StringBuilder();
        if(cookies != null && cookies.length>0){
            for(Cookie item:cookies){
                builder.append(item.getName()+":"+item.getValue()+"<br>");
            }
        }
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().println(builder.toString());
    }
}
